#include "particle_engine.h"

ParticleEngine::ParticleEngine(int pCount)
{
	m_pCount = pCount;
	m_particles = (Particle**)malloc(sizeof(Particle*)*pCount);
	memset(m_particles, 0x00, sizeof(Particle*)*pCount);
}

ParticleEngine::~ParticleEngine(void)
{
	for (int i = 0; i < m_pCount; ++i)
	{
		delete m_particles[i];
		m_particles[i] = '\0';
	}
	
	delete m_particles;
	m_particles = '\0';
}

GLuint ParticleEngine::getTextures(int i)
{
	return textureManager->getTexture(i);
}

void ParticleEngine::initParticles(void)
{
	doInitParticles();
}

void ParticleEngine::updateParticles(void)
{
	doUpdateParticles();
}

void ParticleEngine::drawParticles(void)
{
	doDrawParticles();
}

void ParticleEngine::setTextureManager(TextureManager *txManager)
{
	textureManager = txManager;
}

ExplosionPE::ExplosionPE(int pCount) : ParticleEngine(pCount)
{
	doInitParticles();
}


ExplosionPE::~ExplosionPE(void)
{
	//
}

void ExplosionPE::doInitParticles(void)
{	
	for (int j = 0; j < m_pCount; ++j)
	{
		m_particles[j] = new Particle();
		m_particles[j]->x = ((rand()%(RAND_MAX+1))/(RAND_MAX+1.0f))*5.0f-2.5f;//+(((rand()%(RAND_MAX+1))*2.0f)-1.0f);
		m_particles[j]->y = ((rand()%(RAND_MAX+1))/(RAND_MAX+1.0f))*5.0f-2.5f;//+(((rand()%(RAND_MAX+1))*2.0f)-1.0f);
		GLfloat angle = (rand()%(RAND_MAX+1))/(RAND_MAX+1.0f)*365.0f;
		GLfloat modulo = (rand()%(RAND_MAX+1))/(RAND_MAX+1.0f)*0.05f;
		m_particles[j]->velocity = Vector2D(modulo*cos(angle), modulo*sin(angle));
	}
}

void ExplosionPE::doUpdateParticles(void)
{
	for (int i = 0; i < m_pCount; ++i)
	{	
		m_particles[i]->x += m_particles[i]->velocity.x;
		m_particles[i]->y += m_particles[i]->velocity.y;
		m_particles[i]->velocity.reduce(0.999f);
	}
}
void ExplosionPE::doDrawParticles(void)
{
	
	glColor3f(0.8f,0.6f,0.0f);
	glBindTexture(GL_TEXTURE_2D, getTextures(0));
	
	for (int i = 0; i < m_pCount; ++i)
	{
		glPushMatrix();
		glTranslatef(m_particles[i]->x, m_particles[i]->y, 0.0f);
		glBegin(GL_QUADS);
		
		glTexCoord2f(0.0f, 0.0f);
		glVertex2f(-0.2f,0.2f);
		glTexCoord2f(0.0f, 1.0f);
		glVertex2f(0.2f,0.2f);
		glTexCoord2f(1.0f, 1.0f);
		glVertex2f(0.2f,-0.2f);
		glTexCoord2f(1.0f, 0.0f);
		glVertex2f(-0.2f,-0.2f);
		glEnd();
		glPopMatrix();
	}

	glEnd();
	
}
